﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace Dot5Demo.Utils
{
    /// <summary>
    /// 序列化帮助类
    /// </summary>
    internal class NSerializeUtil
    {

    }

    public class JonsSerialUtil
    {
        public static string Serialize<T>(T t, params JsonConverter[] crs)
        {
            if (t == null)
                return null;
            try
            {
                var options = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    FloatFormatHandling = FloatFormatHandling.String,
                    FloatParseHandling = FloatParseHandling.Double,
                };
                if (crs.Length > 0)
                {
                    for (int i = 0; i < crs.Length; i++)
                    {
                        if (crs[i] != null)
                            options.Converters.Add(crs[i]);
                    }
                }
                return JsonConvert.SerializeObject(t, options);
            }
            catch (Exception ex)
            {
#pragma warning disable CA2200 // 再次引发以保留堆栈详细信息
                throw ex;
#pragma warning restore CA2200 // 再次引发以保留堆栈详细信息
            }
        }
        public static T Deserialize<T>(string str, params JsonConverter[] crs)
        {
            if (str == null)
                return default(T);
            try
            {
                var options = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    FloatFormatHandling = FloatFormatHandling.String,
                    FloatParseHandling = FloatParseHandling.Double,
                    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                };
                if (crs.Length > 0)
                {
                    for (int i = 0; i < crs.Length; i++)
                    {
                        if (crs[i] != null)
                            options.Converters.Add(crs[i]);
                    }
                }
                return JsonConvert.DeserializeObject<T>(str, options);
            }
            catch (Exception ex)
            {
#pragma warning disable CA2200 // 再次引发以保留堆栈详细信息
                throw ex;
#pragma warning restore CA2200 // 再次引发以保留堆栈详细信息
            }
        }
    }

}